package com.jaya.budan.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jaya.budan.R;
import com.jaya.budan.adapter.HorizontalListViewAdapter;
import com.jaya.budan.adapter.Photo_Album_Adapter;
import com.jaya.budan.adapter.Topic_ListViewAdapter;
import com.jaya.budan.base.BaseActivity;
import com.jaya.budan.bean.User_Limit;
import com.jaya.budan.connect.RequestConnect;
import com.jaya.budan.utils.ToolUtils;
import com.jaya.budan.utils.VolleyUtil;
import com.jaya.budan.views.CommonPopWindow;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Publish_Activity extends BaseActivity implements View.OnClickListener, CommonPopWindow.ViewClickListener {

    private RelativeLayout back;
    private RelativeLayout rl_publish_add_topic, rl_publish_location, rl_publish_secret;
    private Button btn_main_publish;
    private ImageView iv_publish_img;
    private TextView tv_feedback_count, tv_publish_secret;
    private EditText et_feedback;
    private String access_token, path, image_path, circle_id, address, longitude, latitude;
    private int type_sercet;
    private View view;
    private List<User_Limit> user_limitList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view = View.inflate(this, R.layout.activity_publish, null);
        setContentView(R.layout.activity_publish);
        Intent intent = getIntent();
        access_token = intent.getStringExtra("access_token");
        image_path = intent.getStringExtra("image_path");
        path = intent.getStringExtra("path");
        SharedPreferences preferences = getSharedPreferences("gd_amapLocation", Context.MODE_PRIVATE);
        longitude = preferences.getString("longitude", "161.231");//经度
        latitude = preferences.getString("latitude", "40.231");//纬度
        back = findViewById(R.id.back);
        rl_publish_add_topic = findViewById(R.id.rl_publish_add_topic);
        rl_publish_location = findViewById(R.id.rl_publish_location);
        rl_publish_secret = findViewById(R.id.rl_publish_secret);
        btn_main_publish = findViewById(R.id.btn_main_publish);
        et_feedback = findViewById(R.id.et_feedback);
        iv_publish_img = findViewById(R.id.iv_publish_img);
        tv_feedback_count = findViewById(R.id.tv_feedback_count);
        tv_publish_secret = findViewById(R.id.tv_publish_secret);
        back.setOnClickListener(this);
        rl_publish_add_topic.setOnClickListener(this);
        rl_publish_location.setOnClickListener(this);
        rl_publish_secret.setOnClickListener(this);
        btn_main_publish.setOnClickListener(this);
        Glide.with(Publish_Activity.this).load(image_path).apply(new RequestOptions()
                                .placeholder(R.mipmap.banner).error(R.mipmap.banner)
                                .diskCacheStrategy(DiskCacheStrategy.NONE)//关闭Glide的硬盘缓存机制
                ).into(iv_publish_img);
        et_feedback.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tv_feedback_count.setText(count + "/512");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_main_publish:
                JSONObject object = new JSONObject();
                Set<String> list_style = new HashSet<>();
                list_style.add(path);
                try {
                    object.put("content", et_feedback.getText().toString().trim());
                    object.put("files", GeRen_Update_Msg_Activity.join2(list_style));
                    object.put("circle_id", circle_id);
                    object.put("role", type_sercet);//	权限 1所有人2粉丝3仅个人可看
                    object.put("longitude", longitude);
                    object.put("latitude", latitude);
                    object.put("address", address);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                postData(object);
                break;
            case R.id.rl_publish_add_topic:
                postData(v);
                break;
            case R.id.rl_publish_location:
                CommonPopWindow.newBuilder()
                        .setView(R.layout.pop_publish_search)
                        .setAnimationStyle(R.style.AnimUp)
                        .setBackgroundDrawable(new BitmapDrawable())
                        .setSize(0, 1100)
                        .setViewOnClickListener(this)
                        .setBackgroundDarkEnable(true)
                        .setBackgroundAlpha(0.7f)
                        .build(this)
                        .showAsCenter(v);
                break;
            case R.id.rl_publish_secret:
                CommonPopWindow.newBuilder()
                        .setView(R.layout.pop_publish_secret)
                        .setAnimationStyle(R.style.AnimUp)
                        .setBackgroundDrawable(new BitmapDrawable())
                        .setSize(0, 800)
                        .setViewOnClickListener(this)
                        .setBackgroundDarkEnable(true)
                        .setBackgroundAlpha(0.7f)
                        .build(this)
                        .showAsCenter(v);
                break;
            case R.id.back:
                CommonPopWindow.newBuilder()
                        .setView(R.layout.pop_geren_fans_cancle)
                        .setAnimationStyle(R.style.AnimUp)
                        .setBackgroundDrawable(new BitmapDrawable())
                        .setSize(0, 600)
                        .setViewOnClickListener(this)
                        .setBackgroundDarkEnable(true)
                        .setBackgroundAlpha(0.7f)
                        .build(this)
                        .showAsCenter(v);
                break;
            default:
                break;
        }
    }

    /**
     * 网络请求
     * @param object
     */
    private void postData(JSONObject object) {
        Log.d("publish", object.toString());
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, RequestConnect.square_publish_Url + access_token, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("publish", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONObject info = jsonObject.getJSONObject("info");
                        String id = info.getString("id");
                        ToolUtils.showToast(Publish_Activity.this, message);
                        finish();
                    } else {
                        ToolUtils.showToast(Publish_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(Publish_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    /**
     * 网络请求
     */
    private void postData(View v) {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, RequestConnect.topic_qz_list_Url + access_token, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("publish", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONArray info = jsonObject.getJSONArray("info");
                        user_limitList = gson.fromJson(info.toString(), new TypeToken<List<User_Limit>>(){}.getType());
                        CommonPopWindow.newBuilder()
                                .setView(R.layout.pop_publish_add_topic)
                                .setAnimationStyle(R.style.AnimUp)
                                .setBackgroundDrawable(new BitmapDrawable())
                                .setSize(0, 600)
                                .setViewOnClickListener(Publish_Activity.this)
                                .setBackgroundDarkEnable(true)
                                .setBackgroundAlpha(0.7f)
                                .build(Publish_Activity.this)
                                .showAsCenter(v);
                    } else {
                        ToolUtils.showToast(Publish_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(Publish_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    @SuppressLint({"NonConstantResourceId", "SetTextI18n"})
    @Override
    public void getChildView(final PopupWindow mPopupWindow, View view, int mLayoutResId) {
        switch (mLayoutResId) {
            case R.layout.pop_geren_fans_cancle:
                TextView tv_cancle = view.findViewById(R.id.tv_cancle);
                TextView tv_geren_fans_cancle = view.findViewById(R.id.tv_geren_fans_cancle);
                TextView img_guanbi = view.findViewById(R.id.img_guanbi);
                tv_geren_fans_cancle.setText("是否放弃对资料的修改");
                tv_cancle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                        finish();
                    }
                });
                img_guanbi.setText("继续编辑");
                img_guanbi.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                    }
                });
                break;
            case R.layout.pop_publish_secret:
                ImageView iv_pop_publish_close = view.findViewById(R.id.iv_pop_publish_close);
                ListView lv_pop_diandian_cancle = view.findViewById(R.id.lv_pop_diandian_cancle);
                Map<Integer, String> photo_data = new HashMap<>();
                List<Integer> list = new ArrayList<>();
                List<String> list2 = new ArrayList<>();
                photo_data.put(1 ,"所有人");
                photo_data.put(2, "仅我关注的人");
                photo_data.put(2, "仅关注我的粉丝");
                photo_data.put(2, "我关注的人及关注我的粉丝");
                photo_data.put(3, "仅自己");
                for (Integer key : photo_data.keySet()){
                    list.add(key);
                }
                for (Integer key : photo_data.keySet()){
                    list2.add("" + photo_data.get(key));
                }
                lv_pop_diandian_cancle.setAdapter(new Photo_Album_Adapter(this, list2, null, null, 2));
                lv_pop_diandian_cancle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        mPopupWindow.dismiss();
                        type_sercet = list.get(position);
                        tv_publish_secret.setText("" + list2.get(position));
                    }
                });
                iv_pop_publish_close.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                    }
                });
                break;
            case R.layout.pop_publish_add_topic:
                ImageView iv_pop_publish_close2 = view.findViewById(R.id.iv_pop_publish_close);
                GridView gv_pop_diandian_cancle = view.findViewById(R.id.gv_pop_diandian_cancle);
                gv_pop_diandian_cancle.setHorizontalSpacing(15);
                gv_pop_diandian_cancle.setVerticalSpacing(15);
                gv_pop_diandian_cancle.setAdapter(new Topic_ListViewAdapter(Publish_Activity.this, user_limitList, null, 3));
                gv_pop_diandian_cancle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        mPopupWindow.dismiss();
                        circle_id = user_limitList.get(position).getId();
                    }
                });
                iv_pop_publish_close2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                    }
                });
                break;
            case R.layout.pop_publish_search:
                TextView tv_publish_no = view.findViewById(R.id.tv_publish_no);
                EditText et_chat_sousuo = view.findViewById(R.id.et_chat_sousuo);
                ImageView iv_pop_publish_close3 = view.findViewById(R.id.iv_pop_publish_close);
                ListView lv_pop_diandian_cancle2 = view.findViewById(R.id.lv_pop_diandian_cancle);
                PoiSearch.Query query = new PoiSearch.Query(et_chat_sousuo.getText().toString().trim(), "", "鹤壁市");//第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国
                query.setPageSize(20);
                query.setPageNum(0);
                PoiSearch search = new PoiSearch(this, query);
                search.setBound(new PoiSearch.SearchBound(new LatLonPoint(Double.parseDouble(latitude), Double.parseDouble(longitude)), 10000));
                search.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
                    @Override
                    public void onPoiSearched(PoiResult poiResult, int i) {
                        PoiSearch.Query query = poiResult.getQuery();
                        List<PoiItem> list = poiResult.getPois();
                        List<SuggestionCity> list_citys = poiResult.getSearchSuggestionCitys();
                        Log.d("publish", "3333" + JSON.toJSON(list));
                        Log.d("publish", "4444" + JSON.toJSON(list_citys));
                        for (PoiItem item : list){
                            Log.d("publish", item.getCityName());
                            Log.d("publish", item.getBusinessArea());
                            Log.d("publish", item.getSnippet());
                            Log.d("publish", item.getLatLonPoint() + "");
                            Log.d("publish", item.getLatLonPoint().getLongitude() + "经度");
                            Log.d("publish", item.getLatLonPoint().getLatitude() + "纬度");
                        }
                        if (list.size() > 0){
                            lv_pop_diandian_cancle2.setAdapter(new HorizontalListViewAdapter(Publish_Activity.this, 0, null, list, 1));
                            lv_pop_diandian_cancle2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    mPopupWindow.dismiss();
                                    address = list.get(position).getProvinceName() + list.get(position).getCityName() +
                                    list.get(position).getAdName() + list.get(position).getSnippet();
                                }
                            });
                        }
                    }

                    @Override
                    public void onPoiItemSearched(PoiItem poiItem, int i) {

                    }
                });
                search.searchPOIAsyn();
                tv_publish_no.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                        address = "不显示";
                    }
                });
                iv_pop_publish_close3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                    }
                });
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            CommonPopWindow.newBuilder()
                    .setView(R.layout.pop_geren_fans_cancle)
                    .setAnimationStyle(R.style.AnimUp)
                    .setBackgroundDrawable(new BitmapDrawable())
                    .setSize(0, 600)
                    .setViewOnClickListener(this)
                    .setBackgroundDarkEnable(true)
                    .setBackgroundAlpha(0.7f)
                    .build(this)
                    .showAsCenter(view);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
